var config = require('../../utils/config');
var API_URL = config.API_URL;
var util = require('../../utils/util');
var app = getApp();
var getUserData = function (that) {
    var userData;
    var url = API_URL.userCenter;
    util.PRL(url, {}).then(res => {
        console.log(res);
        let data = res.data.data;
        let userInfo = res.data.data.userInfo
        console.log(res.data.data.userInfo.avatar)
        if (data.userInfo.liveStatus == 1) {
            data.live_btn = 'open';
        } else if (data.userInfo.liveStatus == 0) {
            data.live_btn = 'close';
        } else {
            data.live_btn = 'disabled';
        }
        app.globalData.balance = data.userInfo.balance;
        that.setData(data);
        that.setData({
            userInfo: userInfo
        })
        if (data.userInfo.certificationInfo.certificationStatus = 1) {
            my.setStorage({
                key: 'hasIdentified',
                data: true,
            })
        }
    }).catch(res => {
        console.log(res);
    })
}
function checkLogin(fn, errOperation) {
    return function (obj = {}) {
        return new Promise((resolve, reject) => {
            console.log(obj)
            obj.success = function (res) {
                console.log(res)
                my.stopPullDownRefresh();
                if (res.headers.Authorization) {
                    console.log(res.headers.Authorization);
                    my.setStorageSync({
                        key: "loginTokenValue",
                        data: {
                            loginToken: res.headers.Authorization
                        }
                    });
                }
                if (res.status == 500) {
                    showNotice('服务器出了点小问题');
                    return
                }
                if (res.status == 200) {
                    resolve(res)
                } else if (status == 400) {
                    let page = getCurrentPages();
                    let length = page.length;
                    let app = getApp();
                    console.log(page);
                    if (length == 1) {
                        app.globalData.routeF = 'switchTab';
                    } else {
                        app.globalData.routeF = 'redirectTo';
                    }
                    var url = '/' + page[length - 1].route;
                    var options = page[length - 1].options;
                    if (options != undefined) {
                        url += '?';
                        for (var key in options) {
                            url = url + key + '=' + options[key] + '&';
                        }
                        url = url.slice(0, -1)
                    }
                    console.log('url:' + url);
                    app.globalData.route = url;
                    my.redirectTo({
                        url: '/pages/login/login',
                    })
                    return
                } else {
                    if (errOperation) {
                        resolve(res)
                    } else {
                        my.hideLoading();
                        my.showModal({
                            title: '提示',
                            content: res.data.msg,
                            showCancel: false
                        })
                    }
                }
            }
            obj.fail = function (res) {
                console.log("失败")
                reject(res)
            }
            fn(obj)

        })
    }
}
let change = that => {
    var Authorization = my.getStorageSync({ key: 'loginToken' }).data;
    console.log(Authorization)
    var timestamp = Date.parse(new Date()) / 1000;
    var obj;
    obj = {
        url: API_URL.change_live,
        method: 'GET',
        headers: {
            Authorization: Authorization,
            timestamp: timestamp
        }
    }
    var postRequest = checkLogin(my.httpRequest, that)
    
    return postRequest(obj)
}
// 实名认证
let goToCer = that => {
    my.confirm({
        title: '提示',
        content: '您还没有实名认证',
        confirmButtonText: '去认证',
        success: function (res) {
            if (res.confirm) {
                my.navigateTo({
                    url: '/pages/user/certification/certification',
                })
            } else if (res.cancel) {
                console.log('用户点击取消')
            }
        }
    })
}
let goToTel = that => {
    my.confirm({
        title: '提示',
        content: '您还没有绑定手机号',
        confirmButtonText: '去绑定',
        success: function (res) {
            if (res.confirm) {
                my.navigateTo({
                    url: '/pages/user/account/bind?name=手机&typ=mobile',
                })
            } else if (res.cancel) {
                console.log('用户点击取消')
            }
        }
    })
}
let goToLive = that => {
    my.confirm({
        title: '提示',
        content: '您还没有绑定直播间',
        confirmButtonText: '去绑定',
        success: function (res) {
            if (res.confirm) {
                my.navigateTo({
                    url: '/pages/user/bind-live/bind-live?phone=' + that.data.userInfo.bindInfo.mobile,
                })
            } else if (res.cancel) {
                console.log('用户点击取消')
            }
        }
    })
}
Page({
    data: {
        "userInfo": {
            "balance": 100,
            "avatar": "",
            "name": "",
            "bindStatus": {
                "hasBindMobile": "0",
                "hasBindLive": "0",
                "hasIdentified": "0"
            },
            "bindInfo": {
                "mobile": "",
                "liveType": "",
                "liveNumberLink": ""
            }
        },
        "demand": {
            "finished": 0,
            "unfinished": 0
        },
        "order": {
            "unpaid": 0,
            "notShipped": 0,
            "notTakeOver": 0
        },
        getUserInfo: {},
        live_btn: 'close'
    },
    onLoad: function () {
        let that = this;
        my.getAuthCode({
            scopes: 'auth_user',
            success: (res) => {
                my.getAuthUserInfo({
                    success: (res) => {
                        that.setData({
                            // getUserName: res.nickName,
                            // getUserAvatr:res.avatar
                            getUserInfo: res
                        })
                    }
                });
            },
        });
        console.log(that.data.getUserInfo)
    },
    onShow: function (options) {
        let that = this;
        if (app.globalData.goToOrder) {
            my.navigateTo({
                url: '/pages/user/order/order?id=0',
            })
            return;
        }
        let isTGX = my.getStorageSync({ key: 'isTGX' }).data;

        that.setData({
            isTGX: isTGX
        })
        let timer = setInterval(function () {
            if (!app.globalData.request) {
                getUserData(that);
                clearInterval(timer);
            }
            my.getStorage({
                key: 'isTGX',
                success: function (res) {
                    if (!res.data) {
                        my.navigateTo({
                            url: "/pages/login/login"
                        });
                    }
                },
                fail: function (res) {

                }
            });
        }, 1000)
    },
    // 跳转求购
    goToDemand: function (e) {
        var typ = e.currentTarget.dataset.typ;
        my.navigateTo({
            url: '/pages/demand/manger/manger?status=' + typ
        })
    },
    // 绑定直播间
    live_toggle: function () {
        let that = this;
        if (that.data.userInfo.bindStatus.hasBindLive != 1) {
            // 没有绑定电话号码
            if (that.data.userInfo.bindStatus.hasBindMobile != 1) {
                my.hideLoading();
                goToTel(that);
            } else {
                // 没有实名认证
                if (that.data.userInfo.bindStatus.hasIdentified != 1) {
                    my.hideLoading();
                    goToCer(that);
                } else {
                    // 绑定直播间
                    my.hideLoading();
                    goToLive(that);
                }
            }
        } else {
            let live_btn = that.data.live_btn;
            change(that)
                .then(res => {
                    console.log(res)
                    my.showToast({
                        content: res.data.msg,
                        type: 'success',
                        duration: 800
                    })
                    if (live_btn == 'close') {
                        live_btn = 'open';
                    } else {
                        live_btn = 'close';
                    }
                    that.setData({
                        live_btn: live_btn
                    })
                }).catch(res => {
                    console.log(res)
                })
        }
    },
    // 用户信息跳转
    goToUser: function (e) {
        my.navigateTo({
            url: '/pages/user/info/info'
        })
    },
    // 订单信息
    goToOrder: function (e) {
        var id = e.currentTarget.dataset.id;
        my.navigateTo({
            url: '/pages/user/order/order?id=' + id
        })
    },
    // 用户余额
    goToBalance: function (e) {
        app.globalData.balance = this.data.userInfo.balance
        my.navigateTo({
            url: '/pages/user/balance/balance?isSetPW=' + this.data.userInfo.isSetPaymentPassword
        })
    },
    // 我的足迹
    goToFoot: function (e) {
        my.navigateTo({
            url: '/pages/user/footer/footer'
        })
    },
    // 我的收藏
    goToCollection: function (e) {
        my.navigateTo({
            url: '/pages/user/collection/collection'
        })
    },
    // 购物车
    goToCart: function (e) {
        my.navigateTo({
            url: '/pages/cart/cart'
        })
    },
    goToNext: function (e) {
        my.navigateTo({
            url: '/pages/user/next/next'
        })
    },
    goToMoney: function (e) {
        my.navigateTo({
            url: '/pages/user/money/money'
        })
    },
    // 我的推荐
    goToRecommend: function (e) {
        my.navigateTo({
            url: '/pages/demand/recommend/recommend',
        })
    },
    goToSet: function (e) {
        my.navigateTo({
            url: '/pages/user/setting/setting'
        })
    }
})